/**
 * @file api.ts
 * @author zhaoli
 *
 * 接口请求文件
 */
import axios from 'axios';
// import { Http } from '../services/Http';
import Http from '../util/http';
import { message, Modal, } from 'antd';
import ls from '../util/localStorage'
import { CommonData } from '../basicData/data';

const http = new Http();

/**
 * http request 拦截器
 */
http.request(
    (config: any) => {
        const token = ls.get('token')
        // 每次发送请求之前检测都localStorage存有token,那么都要放在请求头发送给服务器
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (err: any) => {
        return Promise.reject(err)
    }
)
/**
* http response 拦截器
*/
http.response(
    (res: any) => {
        if (res.status === 200) {
            return Promise.resolve(res);
        } else {
            message.error(res.error.message);
            return Promise.reject(res);
        }
    },
    (err: any) => {
        if (err.response) {
            const status = err.response.status;
            if (status === 500) {
                message.error('服务器错误');
            } else if (status === 401) {
                Modal.info({
                    title: '未授权',
                    content: '请重新登录或联系管理员增添权限，点击确定即跳转至登陆页',
                    okText: '确定',
                    onOk: () => {
                        ls.remove(['token','effectiveTime','loginTime'])
                        window.location.href = CommonData.LoginURL[process.env.NODE_ENV]
                    }
                });
            } else if (status === 403) {
                Modal.info({
                    title:'权限不足',
                    content: '如有疑问，请联系系统管理员',
                    onOk: () => window.location.href = `${CommonData.AuthPlatformURL[process.env.NODE_ENV]}/home`,
                    okText: '确定'
                })
            } else {
                message.error(err.response.data.error_description);
            }
        } else if (err.config && err.config.timeout) {
            message.error('请求超时，请重新登录或重新执行操作')
          }
        return Promise.reject(err);
    }
);


/**
 * 获取官网首页
 */

/**
 * 登录  
 * 特殊处理，使用formdata传输数据
 */
export const login = (params: any) => axios({
    url: '/connect/token',
    method: 'post',
    data: params,
    transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
    }],
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

/**
 * 用户注册
 * @param params 
 * "userCode": "string",
  "userName": "string",
  "userRealName": "string",
  "userRemarks": "string",
  "password": "string",
  "curPassword": "string",
  "gender": "string",
  "age": 0,
  "contact": "string",
  "email": "string",
  "address": "string",
  "telNumber": "string",
  "telNumberExt": "string",
  "level": 0,
  "priority": 0,
  "subordinateCompanyId": 0,
  "id": 0,
  "isActive": true
 */
export const register = (params: object) => http.post('/api/services/app/User/Register', params)
/**
 * 用户注册时判断usercode是否已存在
 * @param params 
 */
export const isUserCodeExist = (code: string) => http.post('/api/services/app/User/IsUserCodeExist', {userCode: code})
/**
 * 获取当前登录用户信息
 */
export const userInfo = () => http.get('/connect/userInfo')

/**
 * 更新个人资料
 * @param data 
 */
export const updateSelfUserInfo = (data: any) => http.put('/api/services/app/User/UpdateSelfUserInfo', data)

/**
 * 用户审批
 * @param userId 用户ID
 */
export const activeUser = (userId: any) => http.post('/api/services/app/User/ActiveUser', userId)
/**
 * 用户升权
 * @param userId 用户ID
 */
export const upgradeUser = (userId: any) => http.post('/api/services/app/User/UpgradeUser', userId)
/**
 * 修改密码
 * @param param 
 */
export const resetPassword = (param: any) => http.post('/api/services/app/User/ResetPassword', param)
/**
 * 管理员重置密码
 * @param param 
 */
export const resetPasswordForAdmin = (id: number, password: string) => http.post('/api/services/app/User/ResetPasswordForAdmin', {
    id: id,
    password: password
})
/**
 * 忘记密码
 */
export const forgetPassword = (userCode: string) => http.post('/api/services/app/User/ForgetPassword', {
    userCode: userCode,
})

/**
 * 获取全部公司
 */
export const getAllCompanys = () => http.get('/api/services/app/Company/GetAllCompanys')
/**
 * 获取权限树
 */
export const getAuthObjectTree = () => http.get('/api/services/app/AuthObject/GetAuthObjectTree')
/**
 * 已处理的消息
 * @param param 消息ID数组 例：[ 0 ]
 */
export const finishedMessage = (param: number[]) => http.post('/api/services/app/Notify/FinishedMessage', param)
/**
 * 发布公告
 * @param param 公告内容
 */
export const sendAnnouncement = (param: string) => http.post('/api/services/app/Notify/SendAnnouncement', {content: param})
/**
 * 获取列表数据
 * @param type 接口名称
 * @param param 需要传的值，过滤条件
 */
export const pagedDatasAsync = (type: string, param: any) => http.post(`/api/services/app/${type}/PagedDatas`, param)
/**
 * 根据ID获取数据详情
 * @param type 接口名称
 * @param id 查询ID
 */
export const getByIdAsync = (type: string, id: number) => http.get(`/api/services/app/${type}/GetById?input=${id}`)
/**
 * 新增或编辑数据
 * @param type 
 * @param param 
 */
export const upsertAsync = (type: string, param: any) => http.post(`/api/services/app/${type}/Upsert`, { entity: param })
/**
 * 批量编辑
 * @param type 
 * @param param 
 */
export const batchUpsertAsync = (type: string, param: any) => http.post(`/api/services/app/${type}/BatchUpsert`, param)
/**
 * 删除某一项
 * @param type 
 * @param id 
 */
export const deleteAsync = (type: string, id: any) => http.delete(`/api/services/app/${type}/Delete?input=${id}`)

/**
 * 批量删除
 * @param type 
 * @param param 需删除的ID的数组
 */
export const batchDeleteAsync = (type: string, param: string[]) => http.post(`/api/services/app/${type}/BatchDelete`, param)
